﻿var aIndex=0;
window.getQuery = function (key) {
    var arr = [],
        obj = {},
        location = window.location.href,
        has = location.indexOf('?') > -1,
        isHash = location.indexOf('#');

    if (!has) return null;
    arr = location.substring(location.indexOf('?') + 1, isHash > -1 ? isHash : location.length).split('&');

    for (var i = 0, len = arr.length; i < len; i++) {
        var temp = arr[i].split('=');
        if (temp.length) obj[temp[0]] = temp[1].replace(/#/g, '');
    }

    if (key) {
        return obj[key];
    } else {
        return obj;
    }
};

$(function () {
    let chapterId = getQuery("id");
    let sort = getQuery("rindex");
    var rIdCurrent = $("#rIdCurrent").val();
    console.log('rIdCurrent:' + rIdCurrent);
    changeIndex (chapterId, sort, rIdCurrent);

    /*var container = $('#layui-container2'),
        scrollTo = $('#intro');
    console.log("scrollTo.offset().top:"+scrollTo.offset().top);
    console.log("container.offset().top:"+container.offset().top);
    console.log("container.scrollTop():"+container.scrollTop());
    container.scrollTop(
        scrollTo.offset().top - container.offset().top + container.scrollTop()
    );*/
});
//$(function () {

function changeIndex (chapterId, sort, rId) {

    var rindexCurrent = $('#rindexCurrent').val();
    var lastRindex = $('#lastRindex').val();
    console.log('rId:' + rId);
    console.log('#index_' + lastRindex);
    console.log('#index_' + sort);
    $('#index_' + lastRindex).attr("style", "text-align: center;");
    $('#index_' + sort).attr("style", "text-align: center;background-color: #009999;");
    $('#lastRindex').val(sort);
    $("#rIdCurrent").val(rId);

    /*$(".layui-container").animate({scrollTop:$("#rsize").offset().top},1000);*/
    var container = $('#layui-container2'),
        scrollTo = $('#intro');

    container.scrollTop(
        scrollTo.offset().top - container.offset().top + container.scrollTop()
    );
   /* var params = {
        chapterId: getQuery("id"),
        sort: getQuery("rindex"),
        id: location.hash.substring(1),
        editorContent: null
    };*/
    var params = {
        chapterId: chapterId,
        sort: sort,
        id: location.hash.substring(1),
        editorContent: null
    };
    var info = {
        restype: {
            0: "none",
            1: "video",
            2: "test",
            3: "discuss",
            4: "doc",
            5: "richtext",
            6: "knowledge"
        },
        get: function () {
            let rsize = $("#rsize").val();
            ////console.log("rsize:"+rsize);
            var width = 188 * rsize;
            $(".course-center .resource").attr("css", "width:" + width + "px!important");
            info.events();
        },
        player: null,
        events: function () {
            var h = this;
            /*初始课程图标*/
            var initIcon = function () {
                var cellNum = Math.floor($(".course-center").width() / 188);
                var cellCount = $(".course-center .cell").length;

                /*页面展示的icon*/
                var index = sort;
                //console.log("index:"+index);

                if (cellCount > cellNum) {
                    if (index > cellCount - cellNum - 1) {
                        $(".resource").css("margin-left", (cellCount - cellNum) * -188 + "px");

                        $(".course-center a:gt('" + (cellCount - cellNum - 1) + "')").each(function () {
                            $(this).addClass("show");
                        });
                    } else if (index <= cellCount - cellNum - 1 && index > cellNum - 1) {
                        $(".resource").css("margin-left", index * -188 + "px");

                        $(".course-center a:gt('" + (index - 1) + "'):lt('" + cellNum + "')").each(function () {
                            $(this).addClass("show");
                        });
                    } else {
                        //前7个（0~6）
                        $(".course-center a:lt('" + cellNum + "')").each(function () {
                            $(this).addClass("show");
                        });
                    }

                    //$("#" + params.id.toString()).addClass("seled");
                } else {
                    /*小于7个*/
                    //$("#" + params.id.toString()).addClass("seled");
                }
            };

            /**左右移动箭头*/
            $(".Qin_micro_lesson .left").bind("click", function () {
                moveIcon("right");
            });

            $(".Qin_micro_lesson .right").bind("click", function () {
                moveIcon("left");
            });

            /*移动图标*/
            var moveIcon = function (type) {
                var cellNum = Math.floor($(".course-center").width() / 188);
                if ($(".course-center a").length > cellNum) {
                    var px;
                    if (type == "left") {
                        if ($(".course-center .show:last").next().length > 0) {
                            if ($(".course-center .cell").index($(".course-center .show:last")) == $(".course-center a").length) {
                                $(".resource").css("margin-left", $(".course-center").width() - $(".resource").width() + "px");
                            } else {
                                px = parseInt($(".resource").css("margin-left")) - 188;
                                $(".resource").css("margin-left", px + "px");
                            }
                            $(".course-center .show:first").removeClass("show");
                            $(".course-center .show:last").next().addClass("show");
                        }
                    } else {
                        if ($(".course-center .show:first").prev().length > 0) {
                            if ($(".course-center .cell").index($(".course-center .show:first")) == 1) {
                                $(".resource").css("margin-left", "0px");
                            } else {
                                px = parseInt($(".resource").css("margin-left")) + 188;
                                $(".resource").css("margin-left", px + "px");
                            }
                            $(".course-center .show:last").removeClass("show");
                            $(".course-center .show:first").prev().addClass("show");
                        }
                    }
                }
            };
            /*初始课程图标*/
            initIcon();
            /*Icon点击操作*/
            $(".cell").click(function () {
                var nowCellId = $(this).data("id");
                if (params.id != nowCellId) {
                    $(".Qin_exam_title a").removeClass("seled");
                    $(this).addClass("seled");
                    info.getView(nowCellId);
                    /*切换hash*/
                    params.id = nowCellId;
                } else {
                    return false;
                }
            });
            info.getView(params.id);
        },
        getView: function (cellId) {
           　var h = this;
            var rIdCurrent = $("#rIdCurrent").val();
            console.log("rIdCurrent:"+rIdCurrent);
            //loading层

            var index = layer.load(1, {
                shade: [0.1,'#fff'] //0.1透明度的白色背景
            });
            $.ajax({
                url: "/couInfo/couInfo/view",
                type: "POST",
                data:{
                    resourceId:rIdCurrent
                },
                dataType: "json",
                success: function(r){
                    console.log("r:"+JSON.stringify(r));
                    if (!r) {
                        return;
                    } else if (r.code < 0) {
                        alert(r.msg);
                        return false;
                    }
                    layer.close(index);
                    h.bindview(r.data);
                },
                error:function(err){
                    //console.log(err.statusText);
                    //console.log('异常');
                }
            });
           /*  /!*加载完毕，按照列表中icon 点击的操作执行*!/
            $.ajax("/couInfo/couInfo/view", {
                resourceId: rIdCurrent
            }, function (r) {
                //console.log("r:"+JSON.stringify(r))
                if (!r) {
                    return;
                } else if (r.code < 0) {
                    alert(r.msg);
                    return false;
                }
                h.bindview(r);
            }, "json");*/
        },
        initReplyData: function (courseId, topicId, sort) {
            var h = this;
            _.ajax("/study/bbs/reply", {
                courseId: courseId,
                topicId: topicId,
                sort: sort
            }, function (r) {
                if (r.code == -1) {
                    alert(r.msg);
                }
                /*页面模板*/
                $("#container").html("");
                $("#container").html(template("reply_html", r));
                /*回复列表模板*/
                $("#replyList").html("");
                $("#replyList").html(template("replyList_html", r));
                _pagination(r.pagination, $("#replyListForm"), "", "#replyList", "replyList_html", h.paginationEvents);
                /*初始化编辑器*/
                info.initUeditor(r);
                info.replyEvents(r);
                //h.commentEvents(r);
            }, "json");
        },
        //绑定视图
        bindview: function (r) {
            var rType = r.type;
           // console.log("rType:"+rType+" "+typeof (rType));
            if(r.type+'' === '1' || r.type+'' === '5'){
                aIndex+=1;
                console.log("aIndex:"+aIndex);
            }

            //console.log("rType:"+rType);
            var h = this;
            /*if(rType+'' != '1'){
                myPlayer = '';
                $(".xianshi").html("");
                $("#intro").html("");
                $(".view_text_con").html("");
            }else {
                $(".view_text_con").html("");
            }*/
            myPlayer = '';
            $(".xianshi").html("");
            $("#intro").html("");
            $(".view_text_con").html("");
            switch (rType+'') {
                case '0':
                    h.initDoc(r);
                    break;
                case '1':
                    info.initVideo(r);
                    break;
                case '2':
                    info.initDoc(r);
                    break;
                case '3':

                    break;
                case '4':
                    info.initDoc(r);
                    break;
                case '5':
                    info.initVideo(r);
                    break;
                default :
                    break;
            }
        },
        initVideo: function (r) {

            //console.log("加载视频!")
            if (r.fileRoute=='') {
                $("#course").html('<div class="noData">暂无数据</div>');
            } else {
               /* if (res.code == 40025 || res.code == 40022) {
                    layer.confirm("您暂未报名此课程，请报名后重试！", {
                        closeBtn: 0,
                        btn: ['返回'],
                        yes: function (index, layero) {
                            window.history.back(-1);
                        }
                    });
                    return false
                }*/

                var intro = '';
                var xianshi = '';
                var a = false;
                if ( r.type == 1 || r.type == 5) {
                    intro += '<input type="hidden" id="isFree" value="' + r.isFree + '" /><h1 style="font-size: 20px;margin-bottom: 10px">视频名称：' + r.name + '</h1><p style="color: #666"><span class="title_1">章节描述：</span>' + r.introduce + '</p><p style="color: #666;margin-top: 10px"><span class="title_1">最短学习时长：</span>' + r.minTime + '分钟</p>';
                    a = true;
                    console.log("aIndex："+aIndex);
                    if(aIndex==0 || aIndex==1){

                    xianshi += '<video id="my-video" class="video-js vjs-big-play-centered" x5-video-player-fullscreen="false" controls preload="auto" width="100%" height="600" data-setup="{}">' +
                        '<source src="' + r.fileRoute + '" type="video/mp4">' +
                        '<source src="' + r.fileRoute + '" type="video/webm">' +
                        '<source src="' + r.fileRoute + '" type="video/ogg">' +
                        '</video>';
                    }else{
                        xianshi += '<div data-setup="{}" preload="auto" x5-video-player-fullscreen="false" class="video-js vjs-big-play-centered vjs-paused my-video-dimensions vjs-controls-enabled vjs-workinghover vjs-v7 vjs-user-active"\n' +
                            '                                         id="my-video" tabindex="-1" lang="zh-cn" role="region" aria-label="视频播放器"\n' +
                            '                                    ><video id="my-video_html5_api" class="vjs-tech"  x5-video-player-fullscreen="false" controls preload="auto" width="100%" height="600" data-setup="{}" tabindex="-1">' +
                            '<source src="' + r.fileRoute + '" type="video/mp4">' +
                            '<source src="' + r.fileRoute + '" type="video/webm">' +
                            '<source src="' + r.fileRoute + '" type="video/ogg">' +
                            '</video> </div>';
                    }

                } else {
                    xianshi += '<div>资源下载：<a download href="' + r.fileRoute + '" style="text-decoration: underline;color: #005C34">' + r.name + '</a></div>'
                }
                //console.log("xianshi:"+xianshi);
                $(".xianshi").html(xianshi);
                $("#intro").html(intro);
                if (a) {
                    myPlayer = videojs('my-video');
                    videojs("my-video").ready(function () {
                        /*var myPlayer = this;
                        myPlayer.play()*/
                    });
                }

            }
        },
        getPoints: function (cellId) {
            var points;
            $.ajax({
                type: "POST",
                url: '/study/directory/getPoints',
                data: {
                    cellId: cellId
                },
                async: false,
                dataType: "json",
                success: function (r) {
                    points = r.cellquestion;
                }
            });

            return points;
        },
        test: function (cuepoint) {
            _.ajax("/study/directory/getVideoTest", {
                cellId: $('input[name=cellId]').val(),
                point: cuepoint
            }, function (r) {
                if (!r || r.code < 0) {
                    //重新播放
                    //info.player.resume()
                    return false;
                }
                info.bindTest(r);
            }, "json");
        },
        bindTest: function (r) {
            /**视频弹框*/
            //dlg.html(edithtml).dialog
            var dlg = $.dynamic_dialog('dlg_video_test').dialog({
                title: "请回答以下问题",
                closeOnEscape: false,
                height: 'auto',
                width: 780,
                modal: true,
                //draggable: false,
                open: function () {
                    //$(".ui-dialog-titlebar-close").hide();
                },
                buttons: [{
                        text: "提交",
                        click: function () {
                            if (info.checkForm(dlg)) {
                                $(".ui-dialog-buttonset button:first").hide();
                                $(".ui-dialog-buttonset button:last").show();
                                $(".answer", dlg).show();
                                $(".ui-dialog-titlebar-close").show();
                            } else {
                                alert("请完成剩余题目！");
                            }
                        }
                    },
                    {
                        text: "关闭",
                        click: function () {
                            dlg.dialog("close");
                        }
                    }
                ]
            }).html(template("videoTest_html", r)).dialog('open');

            //公式编辑器
            //$(".mathquill-embedded-latex").mathquill();

            $(".ui-dialog-buttonset button:last").hide();

            /*加载编辑器*/
            //ajaxeditor.setEditor(".textarea", function (editor) {
            //    $("#custom_load").hide();
            //    $(editor.container).removeClass("edui-editor edui-default");
            //}, { autoHeightEnabled: true, readonly: true, toolbars: [], initialFrameHeight: "30", initialFrameWidth: "100%", contextMenu: [] });

            //ajaxeditor.setEditor(".QA", function (editor) {
            //    $("#custom_load").hide();
            //    $(editor.container).removeClass("edui-editor edui-default");
            //}, { autoHeightEnabled: true, initialFrameHeight: "130", initialFrameWidth: "95%", contextMenu: [] });

            if ($('textarea[name=Selects]', dlg).length > 0) {
                var selectName = 'A';
                for (var i = 0; i < $(".choices", dlg).length; i++) {
                    var num = String.fromCharCode(selectName.charCodeAt() + i);
                    $('.num', dlg).eq(i).text(num);
                    $('input[name=CorrectAnswer]', dlg).eq(i).val(num);
                }
            }

            $(".submit", dlg).click(function () {
                var answers = $('input[name=CorrectAnswer]:checked');
                if (answers.length == 0) {
                    alert("您还没有选中");
                    return false;
                }

                var data = [];
                for (var i = 0, length = answers.length; i < length; i++) {
                    data.push(answers[i].value);
                }

                _.ajax("/study/directory/answerVideo", {
                    questionId: $("input[name=questionId]", dlg).val(),
                    answers: data
                }, function (r) {
                    r = handleException(r);
                    if (!r) {
                        alert("发生未知错误");
                    }

                    course.video.bindResult(dlg, r);
                }, "json");

                return false;
            });
        },
        bindResult: function (dlg, r) {
            dlg.dialog("option", "width", 450).dialog("option", "title", "").html(r);

            $('.close', dlg).click(function () {
                dlg.dialog('close');
                //重新播放
                //info.player.resume()
                return false;
            });

            $('.current', dlg).click(function () {
                _.ajax("/study/directory/getAnaltsis", {
                    questionId: $("input[name=questionId]", dlg).val()
                }, function (r) {
                    r = handleException(r);
                    if (!r) {
                        alert("发生未知错误");
                    }

                    course.video.bindAnalysis(dlg, r);
                }, "json");
            });
        },
        bindAnalysis: function (dlg, r) {
            dlg.dialog("option", "width", 600).dialog("option", "title", "答案解析").html(r);

            $('.ok-btnbor', dlg).click(function () {
                dlg.dialog('close');
                //重新播放
                //info.player.resume()
                return false;
            });
        },
        updateStatus: function (learntime, status) {
            $.ajax({
                type: "POST",
                url: '/study/directory/updateStatus',
                data: {
                    cellId: params.id,
                    learntime: learntime,
                    status: status
                },
                async: false
            });
        },
        checkForm: function (dlg) {
            var isSelected = true;
            $.each($(".preview_item"), function (index) {
                /*视频问题可以不填*/
                //if ($("input:checked", $(this)).length > 0 || $("input[type=checkbox]:checked", $(this)).length > 0) {
                if ($("input:checked", $(this)).length > 0 || jQuery.trim($("input", $(this)).val()).length > 0 || jQuery.trim($("textarea", $(this)).val()).length > 0) {} else {
                    isSelected = false;
                }
            });
            return isSelected;
        },
        checkQA: function () {
            var hasValue = true;

            $(".panel_item").each(function () {
                $("textarea", $(this)).each(function () {
                    if ($(this).val() == "") {
                        hasValue = false;
                    }
                });
            });

            return hasValue;
        },
        initTest: function (r) {
            /*加载模板*/
            $(".view_text_con").html(template("viewTest_html", r));

            /*自动暂存*/
            $(".panel_item[data-type=1] input[type=radio],.panel_item[data-type=2] input[type=checkbox],.panel_item[data-type=4] input[type=radio],.panel_item[data-type=3] input[type=text],.panel_item[data-type=5] textarea").change(function () {
                var _this = $(this);
                if (_this.attr("type") != "checkbox" && !_this.prop("checked")) {
                    return;
                }
                var where = "#" + _this.data("formindex");
                //_.ajax("/study/directory/answerpaper", { paperItemId: $("input[name=paperItemId]").val() }, function (r) {
                $(where).submit_form(function (r) {
                    if (!r) {
                        alert("发生未知错误");
                        return false;
                    }
                }, 'json');
                return false;
            });

            /*提交作业*/
            $(".subpaper").click(function () {
                if (!confirm("确认要提交该作业吗?提交之后不能修改!")) {
                    return;
                }
                _.ajax("/study/directory/subPaper", {
                    studentWorksId: $(".subpaper").data("id")
                }, function (r) {
                    if (r.code < 0) {
                        alert(r.msg);
                        return;
                    } else {
                        alert(r.msg);
                        info.getView(location.hash.substring(1));
                        return;
                    }
                    //course.hashchange();
                }, "json");
                return false;
            });
        },
        initDiscuss: function (r) {
            var topicId = r.cell.ResId;
            // info.initReplyData(params.courseId, r.cell.ResId, $('#orderByTime').data('sort'));
            _.ajax("/study/bbs/reply", {
                courseId: params.courseId,
                topicId: topicId,
                sort: $('#orderByTime').data('sort')
            }, function (o) {
                /*页面模板*/
                $(".view_text_con").html(template("reply_html", o));
                ///*回复列表模板*/
                $("#replyList_div").html(template("replyList_html", o));
                _pagination(o.pagination, $("#replyListForm"), "", "#replyList", "replyList_html", info.paginationEvents);
                info.replyEvents(o);
            }, "json");
        },
        initDoc: function (r) {
            //console.log("r:"+JSON.stringify(r));
            let category = "";
            let extension = "";
            let urls = "";
            let page_count = 1;


            if(r.type+'' == '4'){//图片
                /*extension = r.extension;
                category = "img";
                urls= {
                    "status": "",
                    "preview": r.fileRoute,
                    "download": r.fileRoute,
                    "preview_oss_ori": r.fileRoute,
                    "oss_ori_internal_url": r.fileRoute,
                    "preview_oss_gen": r.fileRoute,
                    "oss_gen_internal_url": r.fileRoute,
                    "owa_url": r.fileRoute,
                    "file_name": r.fileRoute
                }*/
               category = "office";
               extension = "doc";
               urls= {
                   "type":r.type+'',//新增的
                   "status": "",
                   "preview": r.fileRoute,
                   "download": r.fileRoute,
                   "preview_oss_ori": r.fileRoute,
                   "oss_ori_internal_url": r.fileRoute,
                   "preview_oss_gen": r.fileRoute,
                   "oss_gen_internal_url": r.fileRoute,
                   "owa_url": r.fileRoute,
                   "file_name": r.fileName
               }
               page_count = r.pageCount;
            }else {
                category = "office";
                extension = "doc";
                urls= {
                    "type":r.type+'',//新增的
                    "status": "",
                    "preview": r.baseUrl,
                    "download": r.baseUrl,
                    "preview_oss_ori": r.baseUrl,
                    "oss_ori_internal_url": r.baseUrl,
                    "preview_oss_gen": r.baseUrl,
                    "oss_gen_internal_url": r.baseUrl,
                    "owa_url": r.baseUrl,
                    "file_name": r.fileName
                }
                page_count = r.pageCount;
            }



            let newData = {
                "extension": extension,
                "category": category,
                "urls":urls,
                "args":{
                    "page_count":page_count
                },
                "status":2
            }
            /*if(r.pageCount == -1){
                newData.args={};
            }*/

            r.newUrl=JSON.stringify(newData);
            /*加载模板*/
            $(".view_text_con").html(template("doc_html", r));
            if(r.fileRoute!=""){
                var url = $(".docBox").data("url");
                if ($.trim(url).length == 0) {
                    $(".doc_box").html("您查看的资源已删除");
                } else {
                    /*加载预览项*/
                    var mUrl = $(".docBox").attr("data-url");
                    lazy_include({
                        jsFiles: [{
                            url: "/js/cultivateWeb/" + 'resourcePreview.js',
                            cb: function () {
                                $(".docBox").DViewer({
                                    data: mUrl,
                                    baseUrl: "/css/cultivateWeb/",
                                    baseUrl2: "/js/cultivateWeb/"
                                });
                            }
                        }],
                        cssFiles: []
                    });
                }
            }
        },
        initRichtext: function (r) {
            /*加载模板*/
            $(".view_text_con").html(template("richText_html", r));
            //$(".mathquill-embedded-latex").mathquill();
        },
        initUeditor: function (r) {
            /*加载回复显示ueditor*/
            var contentViewOpts = {
                initialFrameWidth: "100%",
                initialFrameHeight: "50",
                wordCount: false,
                readonly: true,
                autoHeightEnabled: true,
                contextMenu: [],
                toolbars: []
            };

            /*主题内容编辑器*/
            var id = info.randomString(10);
            $(".topicContent").attr('id', id);
            jQuery.bindUeditor(id, contentViewOpts);

            /*加载回复*/
            var replyContentOpts = {
                initialFrameWidth: "100%",
                initialFrameHeight: "150",
                wordCount: false,
                readonly: false,
                autoHeightEnabled: true,
                contextMenu: [],
                toolbars: [
                    ['insertimage']
                ]
            };
            var replyContentId = info.randomString(10);
            $(".replyContent").attr('id', replyContentId);
            jQuery.bindUeditor(replyContentId, replyContentOpts);
        },
        paginationEvents: function () {
            var h = this;
            var topicId = $("input[name=topicId]").val();
            var courseId = getQuery("courseId");
            var plateState = $("input[name=plateState]").val();
            var isManager = $("input[name=isManager]").val();
            //加载回复显示ueditor
            ajaxeditor.setEditor(".contentView", function (editor) {
                $(editor.container).css("border", "0");
            }, {
                initialFrameWidth: 'auto',
                initialFrameHeight: '1',
                wordCount: false,
                readonly: true,
                autoHeightEnabled: true,
                contextMenu: [],
                toolbars: []
            });

            function bindCommentList(w) {
                if (plateState == '0' && isManager == 'False') {
                    $(".m-add-comment", w).remove();
                    $(".votebox", w).remove();
                    $(".commentdiv", w).remove();
                }

                //删除回复
                $(".deleteReply", w).off("click").on("click", function () {
                    if (!confirm("确认删除？")) {
                        return;
                    }
                    var _this = $(this);
                    var id = _this.data("id");
                    jQuery.post("/study/bbs/deleteReply", {
                        topicId: topicId,
                        id: id,
                        courseId: courseId
                    }, function (r) {
                        if (r.code == 1) {
                            alert("删除成功");
                            if (r.parentId == "") {
                                _.ajax("/study/bbs/reply", {
                                    courseId: courseId,
                                    topicId: topicId
                                }, function (r) {
                                    $("#replyList_div").html(template("replyList_html", r));
                                    _pagination(r.pagination, $("#replyListForm"), "", "#replyList_div", "replyList_html", info.paginationEvents);
                                });
                            } else {
                                var commentForm = _this.parents("form");
                                commentForm.submit_form(function (r) {
                                    $(".commentList_div", commentForm).html(template("commentList_html", r));
                                    _pagination(r.pagination, commentForm, null, ".commentList_div", "commentList_html", bindCommentList(commentForm), 1);
                                });
                                _this.parents(".m-commentWrapper").prev().find(".comment").text("评论(" + r.commentCount + ")");
                            }
                        } else {
                            alert(r.msg);
                        }
                    }, "json");
                    return false;
                });

                //顶踩
                $(".upVote,.downVote", w).off("click").on("click", function () {
                    var _this = $(this);
                    var id = _this.next().data("id");
                    var type = 1;
                    if (_this.hasClass("down")) {
                        type = -1;
                        id = _this.prev().data("id");
                    }
                    jQuery.post("/study/BBS/upVote", {
                        courseId: courseId,
                        id: id,
                        type: type
                    }, function (r) {
                        if (r.code == 1) {
                            _this.parent().find(".num").text(r.sumVote);
                            _this.siblings(".hvr").removeClass("voted");
                            _this.addClass("voted");
                            if (_this.hasClass("down")) {
                                _this.siblings(".hvr").attr("title", "顶");
                                _this.attr("title", "取消踩");
                            } else {
                                _this.siblings(".hvr").attr("title", "踩");
                                _this.attr("title", "取消顶");
                            }
                        } else {
                            _this.parent().find(".num").text(r.sumVote);
                            if (_this.hasClass("down")) {
                                _this.attr("title", "踩");
                            } else {
                                _this.attr("title", "顶");
                            }
                            _this.removeClass("voted");
                        }
                    }, "json");
                    return false;
                });

                //评论置顶
                $(".makeCommentTop").off("click").on("click", function () {
                    var _this = $(this);
                    var id = _this.parents(".commentId").data("id");
                    var _form = _this.parents("form");
                    jQuery.post("/study/bbs/replyTop", {
                        id: id
                    }, function (r) {
                        if (r.code == 1 && !r.isTop) {
                            $(".u-forumtag").show();
                            alert("置顶成功");
                            _form.submit_form(function (r) {
                                $(".commentList_div", _form).html(template("replyList_html", r));
                                _pagination(r.pagination, $(".getComment", _form), "", ".commentList_div", "commentList_html", bindCommentList(_form), 1);
                            });
                        } else if (r.code == 1 && !r.isTop) {
                            $(".u-forumtag").hide();
                            alert("取消成功");
                            _form.submit_form(function (r) {
                                $(".commentList_div").html(template("replyList_html", r));
                                _pagination(r.pagination, $(".getComment", _form), "", ".commentList_div", "commentList_html", bindCommentList(_form), 1);
                            });
                        }
                    }, "json");
                });
            }

            //回复置顶
            $(".makeReplyTop").off('click').on("click", function () {
                var id = $(this).data("id");
                _.ajax("/study/bbs/replyTop", {
                    id: id
                }, function (r) {
                    if (r.code == 1 && r.isTop) {
                        $(".u-forumtag").show();
                        alert("置顶成功");
                        _.ajax("/study/bbs/reply", {
                            courseId: courseId,
                            topicId: topicId
                        }, function (r) {
                            $("#replyList_div").html(template("replyList_html", r));
                            _pagination(r.pagination, $("#replyListForm"), "", "#replyList_div", "replyList_html", info.paginationEvents);
                        });
                    } else if (r.code == 1 && !r.isTop) {
                        $(".u-forumtag").hide();
                        alert("取消成功");
                        _.ajax("/study/bbs/reply", {
                            courseId: courseId,
                            topicId: topicId
                        }, function (r) {
                            $("#replyList_div").html(template("replyList_html", r));
                            _pagination(r.pagination, $("#replyListForm"), "", "#replyList_div", "replyList_html", info.paginationEvents);
                        });
                    } else {
                        alert(r.msg);
                    }
                }, "json");
            });

            //评论
            $(".comment").click(function () {
                var list = $(this).parents(".m-detailInfoItem").siblings(".comment_list");
                if (list.hasClass("hidden")) {
                    list.find(".getComment").submit_form(function (r) {
                        $(".commentList_div", list).html(template("commentList_html", r));
                        _pagination(r.pagination, $(".getComment", list), "", ".commentList_div", "commentList_html", bindCommentList, 1);
                    });
                    list.removeClass("hidden");
                    return false;
                }
                list.addClass("hidden");
                return false;
            });

            var isComment = false;
            //添加评论
            $(".addComment").off("click").on("click", function () {
                if (isComment) {
                    return false;
                }
                var _this = $(this);
                var length = _this.parents("form").find(".commentText").val().length;
                if (length <= 1000 && length > 0) {
                    isComment = true;
                    _this.parents(".commentForm").submit_form(function (r) {
                        if (r.code = 1) {
                            var _form = _this.parents(".m-commentWrapper").find(".getComment");
                            _this.parents(".m-commentWrapper").prev().find(".comment").text("评论(" + r.commentCount + ")");
                            _form.submit_form(function (r) {
                                $(".commentList_div", _form).html(template("commentList_html", r));
                                _pagination(r.pagination, _form, "", ".commentList_div", "commentList_html", bindCommentList(_form), 1);
                            });
                        }
                        isComment = false;
                    });
                    _this.parents("form").find(".commentText").val("");
                } else {
                    alert("评论内容字数需在1-1000之间");
                }
                return false;
            });

            bindCommentList();
            return false;
        },
        replyEvents: function (r) {
            var h = this;
            var editor_reply = {};
            var topicId = $("input[name=topicId]").val();
            var courseId = getQuery("courseId");
            //加载回复
            ajaxeditor.setEditor(".replyContent", function (editor) {
                editor_reply = editor;
            }, {
                initialFrameWidth: '100%',
                wordCount: false,
                autoHeightEnabled: true,
            });

            //加载回复显示ueditor
            ajaxeditor.setEditor(".topicView", function (editor) {
                $(editor.container).css("border", "0");
            }, {
                initialFrameWidth: 'auto',
                initialFrameHeight: '1',
                wordCount: false,
                readonly: true,
                autoHeightEnabled: true,
                contextMenu: [],
                toolbars: []
            });

            var isReply = false;
            /*添加回复*/
            $("#addReply").off('click').on("click", function () {
                if (isReply) {
                    return false;
                }
                if ((jQuery.trim(editor_reply.getContentTxt()) && jQuery.trim(editor_reply.getContentTxt()) != "‍") || $('img', editor_reply.body).length > 0 || $('iframe', editor_reply.body).length > 0) {
                    isReply = true;
                    $("#addCommentForm").submit_form(function (r) {
                        if (!r) {
                            alert("发生未知错误!");
                        } else if (r.code == 1) {
                            //加载评论列表
                            alert(r.msg);
                            _.ajax("/study/bbs/reply", {
                                courseId: courseId,
                                topicId: topicId
                            }, function (r) {
                                $("#replyList_div").html(template("replyList_html", r));
                                _pagination(r.pagination, $("#replyListForm"), "", "#replyList_div", "replyList_html", info.paginationEvents);
                            });
                            //清空编辑器 重新加载数据
                            editor_reply.setContent('');
                        } else {
                            alert(r.msg);
                        }
                        isReply = false;
                        return false;
                    });
                } else {
                    alert("内容不能为空");
                }
                return false;
            });

            //按时间排序
            $("#orderByTime").off('click').on("click", function () {
                var _this = $(this);
                _this.toggleClass("downsort");
                _this.toggleClass("upsort");
                var sort = "";
                if (_this.hasClass("downsort")) {
                    sort = "IsTop,-DateCreated";
                } else {
                    sort = "IsTop,DateCreated";
                }
                _.ajax("/study/bbs/reply", {
                    courseId: courseId,
                    topicId: topicId,
                    sort: sort
                }, function (r) {
                    $("#replyList_div").html(template("replyList_html", r));
                    _pagination(r.pagination, $("#replyListForm"), "", "#replyList_div", "replyList_html", info.paginationEvents);
                });
            });

            //投票数排序
            $("#orderByVote").click(function () {
                var _this = $(this);
                _this.prev().remove("downsort").remove("upsort").addClass("nosort");
                _this.addClass("downsort");
                var sort = "IsTop,-VoteCount";
                _.ajax("/study/bbs/reply", {
                    courseId: courseId,
                    topicId: topicId,
                    sort: sort
                }, function (r) {
                    $("#replyList_div").html(template("replyList_html", r));
                    _pagination(r.pagination, $("#replyListForm"), "", "#replyList_div", "replyList_html", info.paginationEvents);
                });
            });

            //关注
            $("#makeFocus").click(function () {
                var _this = $(this);
                if (_this.hasClass("unfollowed")) {
                    _.ajax("/study/bbs/focusOn", {
                        topicId: topicId,
                        courseId: courseId
                    }, function (r) {
                        if (r.code == 1) {
                            _this.removeClass("unfollowed").addClass("followed");
                            alert(r.msg);
                        } else {
                            alert(r.msg);
                        }
                    }, "json");
                } else {
                    _.ajax("/study/bbs/focusOff", {
                        topicId: topicId
                    }, function (r) {
                        if (r.code == 1) {
                            _this.removeClass("followed").addClass("unfollowed");
                            alert(r.msg);
                        }
                    }, "json");
                }
            });

            //回复
            $("#replyBtn").click(function () {
                window.scrollTo(0, document.body.scrollHeight);
                editor_reply.focus();
            });

            //主题置顶
            $("#makeTop").click(function () {
                var _this = $(this);
                jQuery.post("/study/bbs/topicTop", {
                    topicId: topicId
                }, function (r) {
                    if (r.code == 1 && r.isTop) {
                        _this.removeClass("untop").addClass("top");
                        $("#topTag").show();
                        alert("置顶成功");
                    } else if (r.code == 1 && !r.isTop) {
                        _this.removeClass("top").addClass("untop");
                        $("#topTag").hide();
                        alert("取消成功");
                    } else {
                        alert(r.msg);
                    }
                }, "json");
            });

            //主题删除
            $(".deleteTopic").click(function () {
                if (confirm("确认删除该主题？")) {
                    jQuery.post("/study/bbs/deleteTopic", {
                        ids: topicId
                    }, function (r) {
                        if (r.code == 1) {
                            window.location.href = "/study/bbs/bbs.html?courseId=" + getQuery("courseId") + "&plateId=" + $("#plateId").val();
                        }
                    }, "json");
                }
                return false;
            });
            return false;
        },
        randomString: function (len) {
            len = len || 32;
            var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
            var maxPos = $chars.length;
            var pwd = '';
            for (var i = 0; i < len; i++) {
                pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return pwd;
        },
        init: function () {
            var h = this;
            h.get();
        },
    };
    var getHashObj = function () {
        var hash = location.hash;
        var index = hash.indexOf("?");
        var url = hash,
            querystring = "";
        if (index != -1) {
            url = hash.substring(1, index);
            querystring = hash.substring(index + 1);
        }
        return {
            hash: hash,
            url: url,
            querystring: querystring
        };
    };
    info.init();
}
//});


